package co.china.lottery.account.service.impl;

import net.blogjava.frankiegao123.log.slf4j.Log;
import net.blogjava.frankiegao123.log.slf4j.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import co.china.lottery.account.annotation.AccountPay;
import co.china.lottery.account.dao.PayAccountDao;
import co.china.lottery.account.dao.entity.LPayAccount;
import co.china.lottery.account.dao.entity.LPayAccountHis;
import co.china.lottery.account.service.CreateAccountService;
import co.china.lottery.account.service.code.PayIncrementCode;
import co.china.lottery.account.service.code.base.Account;
import co.china.lottery.account.util.Tools;

@Component
@AccountPay
public class CreatePayAccountService implements CreateAccountService {

	private final static Log log = LogFactory.getLog(CreatePayAccountService.class);

    @Autowired
    private PayAccountDao payAccountDao;
    
	@Autowired
	private PayAccountService payAccountService;
    
	@Override
	public Account getOrCreateAccount(String agentId, boolean isUsing) {

		LPayAccount payAccount = payAccountDao.findAccountByAgentId(agentId);
        if(payAccount!=null) {
            log.warn("getOrCreateAccount, but pay account already exists, pay account id: {}", payAccount.getId());
            return payAccount;
        }

        payAccount = LPayAccount.getInstance(agentId);
        payAccountDao.save(payAccount);
        LPayAccountHis his = LPayAccountHis.getCommit(payAccount, 0.0, getAccountCode(isUsing), 0l);
        his.setCommitStatus(LPayAccountHis.COMMIT_STATUS_YES);
        double payBalance =  payAccountService.agentAccountQuery(agentId);
        his.setBalanceBefore(payBalance);
        his.setBalanceAfter(Tools.add(payBalance, his.getDebitCredit()));
        payAccountDao.save(his);
        payAccount.setLastHisId(his.getId());
        payAccount.setLastUpdateTime(his.getCreateTime());

        if(isUsing) {
            log.warn("getOrCreateAccount, pay account not exist, CREATE A NEW PAY ACCOUNT, agentId: {}, pay account id: {}", agentId, payAccount.getId());
        } else {
            log.info("getOrCreateAccount, pay account not exists, create success, pay account id: {}", payAccount.getId());
        }
        return payAccount;
    }

    private PayIncrementCode getAccountCode(boolean isUsing) {
        if(isUsing) {
            return PayIncrementCode.CODE_0001;
        }
        return PayIncrementCode.CODE_0000;
    }
}